-- ======================================================================
-- Hell Lua Bus
-- 
-- Copyright 2012-2013Hell-Prototypes
--
-- http://www.hellprototypes.com/
--
-- This is free software, licensed under the terms of the GNU General
-- Public License as published by the Free Software Foundation.
-- ======================================================================
hlb = require('libhlb')
iHEX = require "mod_iHEX"

pgm_hex_file = "Hell_Lua_Bus.hex"
COM_PORT = "COM1"

g_line_feed = 0

display_FW_raw_data = 1

-- -----------------------------------------------------------------------------
function progress_call_back( num )
	if type(num) == "number" then
		if num == -2 then
			print("<IAP> 1. Sync rs232 buffer")
		elseif num == -1 then
			print("<IAP> 2. Set app entry to reset vector")
			
		else
			if g_line_feed == 0 then
				print("<IAP> 3. Start download FW: (0% ~ 100%)")
				io.write("<IAP>    ")
			end
			if g_line_feed >= 16 then
				print("")
				io.write("<IAP>    ")
				g_line_feed = 1
			else
				g_line_feed = g_line_feed + 1
			end		
			io.write(string.format("%02d ", num))
		end
	end
end
-- -----------------------------------------------------------------------------
print("===============================================")
print(hlb._COPYRIGHT_)
print("===============================================")

pgm_raw_data = {}
pgm_start_addr = 0

f=io.open(pgm_hex_file,"r")
if f~=nil then
	io.close(f)
else
	print("<IAP> Error: Program file not exist, file name: " .. pgm_hex_file)
	return
end

pgm_start_addr, pgm_raw_data = iHEX.Read_File(pgm_hex_file)

if type(pgm_raw_data) == "table" then
	if display_FW_raw_data > 0 then
		print("========== Program data - Hex Format ==========")
		for i=1, #pgm_raw_data do
			io.write(string.format("%02x ", pgm_raw_data[i]):upper())
			if i%16 == 0 then
				print("")
			end
		end
		print(string.format("\r\nFW start address = 0x%04x", pgm_start_addr))
		print("===============================================\r\n")
	end
else
	print("<IAP> Error: fail to read hex file.")
	return
end

print("<IAP> Open IAP communicate Port : " .. COM_PORT)
ret = hlb.IAP_open(COM_PORT)
if ret < 0 then
	print("<IAP> Fail to open Port: " .. COM_PORT .. " , ret code = " .. ret)
	return
end

print("<IAP> Start download ...")
ret = hlb.IAP_run(pgm_raw_data, progress_call_back)
print("")
if ret < 0 then
	print("<IAP> Fail to download FW, ret code = " .. ret)
end

print("<IAP> Done ...")

print("<IAP> Close IAP communicate Port")
hlb.IAP_close()

print("<IAP> Hell Lua Bus FW download DONE")
print("<IAP> Note: Repower the target to run new APP")